/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * 函数节流
 * 主要作用于 例如 监听鼠标移动 频繁触发的行为，间隔触发执行
 * @template T
 * @template R
 * @param {(this: T, ...args: any[]) => R} fn
 * @param {number} [wait=100]
 * @param {number} [type=1] 1 使用时间戳 2 使用setTimeout倒计时
 * @returns
 */
export default function throttle<T, R = void>(fn: (this: T, ...args: any[]) => R, wait = 100, type: 1 | 2 = 1) {
  let previous = 0;
  let timer: null | number = null;
  return function (this: T, ...args: any[]) {
    const context = this;
    if (type === 1) {
      const now = Date.now();
      if (now - previous > wait) {
        fn.apply(context, args);
        previous = now;
      }
      return;
    }

    if (timer) window.clearTimeout(timer);
    timer = window.setTimeout(() => {
      fn.apply(context, args);
      timer = null;
    }, wait);
  };
}
